package db

import (
	"database/sql"
	"strconv"
	"strings"

	"lp/class"
	//需要使用mysql
	_ "github.com/go-sql-driver/mysql"
	log "github.com/jeanphorn/log4go"
)

const (
	//配置MySQL的基本信息
	userName = "root"
	password = "1233211234567"
	ip       = "localhost"
	port     = "3306"
	dbName   = "lp"
)

//DB Db数据库连接池
var DB *sql.DB

//InitDB 初始化数据库
func InitDB() {
	//构建连接：“用户名：密码@tcp(IP:端口)/数据库?charset=utf8”
	path := strings.Join([]string{userName, ":", password, "@tcp(", ip, ":", port, ")/", dbName, "?charset=utf8"}, "")

	//打开数据库，第一个参数是驱动名，所以要导入 _ "github.com/go-sql-driver/mysql"
	DB, _ = sql.Open("mysql", path)

	//设置数据库的最大连接数
	DB.SetConnMaxLifetime(100)

	//设置数据库最大闲置连接数
	DB.SetMaxIdleConns(10)

	//验证连接
	if err := DB.Ping(); err != nil {
		log.LOGGER("SERVER").Error("连接数据库失败:%v", err)
		return
	}

	log.LOGGER("SERVER").Info("连接数据库成功")

}

//InsertUser insert 添加一组用户信息
func InsertUser(u class.UserObj) bool {
	addrs := u.ToAddrList()
	valueCount := strings.Repeat("?,", len(addrs)-1)

	_, errInsert := DB.Exec("INSERT INTO user_tb VALUES ("+valueCount+"?)", addrs...)
	if errInsert != nil {
		log.LOGGER("USER").Error("%s:插入用户信息失败:%v", u.UserName, errInsert)
		return false
	}

	log.LOGGER("USER").Info("%s:插入用户信息成功", u.UserName)

	return true
}

//DeleteUserByName 删除一组用户信息
func DeleteUserByName(u class.UserObj) bool {

	_, errDel := DB.Exec("DELETE FROM user_tb WHERE username = ?", u.UserName)
	if errDel != nil {
		log.LOGGER("USER").Error("%s:删除用户出错", u.UserName)
		return false
	}

	log.LOGGER("USER").Info("%s:删除用户成功", u.UserName)

	return true
}

//UpdateUserInfo 更新用户信息(一个字段)
func UpdateUserInfo(u class.UserObj, value interface{}, column string) bool {
	exeStr := "UPDATE user_tb SET " + column + "=? WHERE id=?"

	_, errInsert := DB.Exec(exeStr, value, u.ID)
	if errInsert != nil {
		log.LOGGER("USER").Error("%s:用户字段(%s)更新失败:%v", u.UserName, column, errInsert)
		return false
	}

	log.LOGGER("USER").Info("%s:用户字段(%s)更新成功", u.UserName, column)

	return true
}

//CheckUserInfo 验证用户信息，传入用户名，如果验证通过返回用户所有基本信息
func CheckUserInfo(u class.UserObj) (usr class.UserObj, result bool) {
	result = false
	userTemp := class.UserObj{}
	row := DB.QueryRow("SELECT * FROM user_tb WHERE username = ?", u.UserName)
	err := row.Scan(userTemp.ToAddrList()...)
	if err != nil {
		log.LOGGER("USER").Error("校验信息时映射对象出错:%v", err)
		return
	}

	if userTemp.Password == u.Password || userTemp.Token == u.Token {
		result = true
		usr = userTemp
	}

	return
}

//IsExist 检查这个用户是否存在，如果存在则返回true
func IsExist(u class.UserObj) (exist bool) {
	exist = false

	usr := class.UserObj{}
	row := DB.QueryRow("SELECT * FROM user_tb WHERE username = ?", u.UserName)
	scanErr := row.Scan(usr.ToAddrList()...)
	if scanErr != nil {
		log.LOGGER("USER").Error("检查用户是否存在时映射失败:%v", scanErr)
		return
	}

	log.LOGGER("USER").Info("%s:用户存在", u.UserName)
	exist = true

	return
}

//CreateUserID 生成用户ID
func CreateUserID() string {
	str := "lp"
	//创建接收对象
	u := class.UserObj{}

	//执行查询语句
	row := DB.QueryRow("SELECT * FROM user_tb ORDER BY id DESC LIMIT 1")

	//映射查询结果
	scanErr := row.Scan(u.ToAddrList()...)
	if scanErr != nil {
		log.LOGGER("USER").Error("查询最大ID时映射失败:%v", scanErr.Error())
		return str + "1"
	}

	return str + strconv.Itoa(u.ID+1)
}
